﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.TextUtils;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace CatUtils.Utils.SpecialUtils.ContentRecognition.YoudaoUtils.Translate
{
    /// <summary>
    /// 有道辅助工具
    /// </summary>
    public class YoudaoTool
    {
        /// <summary>
        /// 增加静态client 减少一次请求
        /// </summary>
        public static CWebclient YoudaoClient = null;

        public static string EncryptionKey = "";

        /// <summary>
        /// 初始化有道浏览器
        /// </summary>
        /// <returns></returns>
        public static CWebclient InitWebClient()
        {
            if (YoudaoClient != null)
                return YoudaoClient;
            string Api = "http://fanyi.youdao.com/";
            YoudaoClient = new CWebclient();
            YoudaoClient.GetHtml(Api);
            return YoudaoClient;
        }

        /// <summary>
        /// 获取加密数据
        /// </summary>
        /// <param name="cWebclient"></param>
        /// <returns></returns>
        public string GetEncryption(CWebclient cWebclient)
        {
            if (EncryptionKey != "")
                return EncryptionKey;
            string API = "http://shared.ydstatic.com/fanyi/newweb/v1.0.14/scripts/newweb/fanyi.min.js";
            string Shtml = cWebclient.GetHtml(API);
            string RegText = TextHelper.RegexText(Shtml, "n.md5\\(\"fanyideskweb\"\\+\\w\\+\\w+.*?\\)", RegexOptions.Singleline);
            Console.WriteLine(RegText);
            RegText = TextHelper.ReplaceTextEnhance(RegText, "n.md5\\(\"fanyideskweb\"\\+\\w\\+\\w\\+\"", "").Replace("\")", "");
            Console.WriteLine(RegText);
            EncryptionKey = RegText;
            return RegText;
        }

        /// <summary>
        /// 翻译结果
        /// </summary>
        /// <param name="TranslateContent"></param>
        /// <returns></returns>
        public string Translate(string TranslateContent)
        {
            string Result = GetResult(TranslateContent);
            string ReturnContent = "";
            try
            {
                YoudaoJson.Root root = JsonConvert.DeserializeObject<YoudaoJson.Root>(Result);
                if (root != null)
                    foreach (var item in root.translateResult)
                    {
                        foreach (var tgt in item)
                        {
                            ReturnContent += tgt.tgt;
                        }
                    }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return ReturnContent;
        }

        /// <summary>
        /// 获取翻译结果
        /// </summary>
        /// <param name="TranslateContent"></param>
        /// <returns></returns>
        public string GetResult(string TranslateContent)
        {
            TranslateContent = WebHelper.UrlDeCode(TranslateContent);
            CWebclient Youdaoclient = InitWebClient();
            string Encryption = new YoudaoTool().GetEncryption(Youdaoclient);
            string API = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule";
            WebHeaderCollection webHeaderCollection = WebHelper.PcWebHeader();
            webHeaderCollection.Add("Referer", "http://fanyi.youdao.com/");

            long DataTIme = GetJaveScriptTime() +//模拟获取JS时间戳
#pragma warning disable S125 // Sections of code should not be commented out
                TextHelper.GetRandom(0, 9);//模拟console.log(parseInt(10 * Math.random(), 10));
#pragma warning restore S125 // Sections of code should not be commented out

            string MD5Text = GetMd5(Encryption, TranslateContent, DataTIme);
            string PostData = $"i={TranslateContent}&from=AUTO&to=AUTO&smartresult=dict&client=fanyideskweb&salt={DataTIme}&ts={TextHelper.Substring(DataTIme.ToString(), 0, DataTIme.ToString().Length - 1)}" +
               $"&sign={MD5Text.ToLower()}&bv=e2a78ed30c66e16a857c5b6486a1d326&doctype=json&version=2.1&keyfrom=fanyi.web&action=FY_BY_CLICKBUTTION&typoResult=false";

            return Youdaoclient.SendPost(API, PostData, webHeaderCollection);
        }

        /// <summary>
        /// 获取MD5属性值
        /// </summary>
        /// <param name="encryption"></param>
        /// <param name="translateContent"></param>
        /// <param name="dataTIme"></param>
        /// <returns></returns>
        private string GetMd5(string encryption, string translateContent, long dataTIme)
        {//md5( t + r + "ebSeFb%=XZ%T[KZ)c(sy!")
            string ContentMD5 = "fanyideskweb" + translateContent + dataTIme + encryption;

            return TextGetMd5(ContentMD5);
        }

        /// <summary>
        /// 获取字符串MD5
        /// </summary>
        /// <param name="Utf8Text"></param>
        /// <returns></returns>
        public string TextGetMd5(string Utf8Text)
        {
            byte[] result = Encoding.UTF8.GetBytes(Utf8Text);    //tbPass为输入密码的文本框
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "");  //tbMd5pass为输出加密文本的文本框
        }

        /// <summary>
        /// 获取js时间戳
        /// </summary>
        /// <returns></returns>
        public long GetJaveScriptTime()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }
    }
}